package com.wowangz.cms.systemmanage.exportreport.lucentask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHHelper {
	

	/**
	 * 远程 执行命令并返回结果调用过程 是同步的（执行完才会返回）
	 * @param host	主机名
	 * @param user	用户名
	 * @param psw	密码
	 * @param port	端口
	 * @param command	命令
	 * @return
	 */
	public static Map<String,String> exec(String host,String user,String psw,int port,String command){
		String result="";
		Session session =null;
		ChannelExec openChannel =null;
		Map<String,String> map = new HashMap<String,String>();
		try {
			JSch jsch=new JSch();
			session = jsch.getSession(user, host, port);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.setPassword(psw);
			session.connect();
			openChannel = (ChannelExec) session.openChannel("exec");
			openChannel.setCommand(command);
			openChannel.connect();  
            InputStream in = openChannel.getInputStream();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));  
            String buf = null;
            String filename="";
            map.put(filename, null);//初始化
            while ((buf = reader.readLine()) != null) {
            	result = new String(buf.getBytes("gbk"),"UTF-8"); 
            	filename = result.substring(result.lastIndexOf("/")+1);
            	result = result.substring(0, result.lastIndexOf("/"));
            	result= result.replace("data/AgoraFiles/", "");
            	map.put(filename, result);
            	System.out.println(result);
            }
		} catch (JSchException | IOException e) {
			result+=e.getMessage();
		}finally{
			if(openChannel!=null&&!openChannel.isClosed()){
				openChannel.disconnect();
			}
			if(session!=null&&session.isConnected()){
				session.disconnect();
			}
		}
		return map;
	}
	
	public static Map<String,String> getFilepaths(String date,String fname){
		Map<String,String> map = new HashMap<String,String>();
		
		String ip="114.112.56.134";
		String user="root";
		String pwd = "Alex.xiao1987";
		//String cmd = "find /data/AgoraFiles/"+ date +"/* -name \'"+ fname +"\'";//日期可能不准
		String cmd = "find /data/AgoraFiles/* -name \'"+ fname +"\'";
		map = exec(ip, user, pwd, 22, cmd);
		return map;
	}
	
	public static String getOneFilePath(String date,String fname){
		return getFilepaths(date,fname).get(fname);
	}
	
	
	public static void main(String args[]){
		//exec("114.112.56.134", "root", "Alex.xiao1987", 22, "find /data/AgoraFiles/20161202/* -name '9ba916f58381d117688d989c5fe7e19e.mp4'");
		getOneFilePath("","8e6d27b486486d1f9baf598bc055a570.mp4");
	}
}
